package com.slkj.shilixiaoyuanapp.ui.main.message;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.slkj.shilixiaoyuanapp.R;
import com.slkj.shilixiaoyuanapp.base.ActivityInfo;
import com.slkj.shilixiaoyuanapp.base.BaseActivity;
import com.slkj.shilixiaoyuanapp.entity.contacts.PersonBean;
import com.slkj.shilixiaoyuanapp.util.PinyingUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

@ActivityInfo( layout = R.layout.search_activity ,isShowActionBar = false)
public class SearchActivity extends BaseActivity {
    @BindView(R.id.top_bar_back)
    ImageView back;
    @BindView(R.id.act_employee_search_recyclerview)
    RecyclerView recyclerView;
    @BindView(R.id.act_employee_search_editetext)
    EditText editText;
    @BindView(R.id.act_employee_search_clear)
    ImageView ivClear;
    @BindView(R.id.act_employee_search_ec)
    TextView tvEC;
    @BindView(R.id.act_employee_search_progress)
    ProgressBar progressBar;

    private SearchAdaper adaper;
    private ArrayList<PersonBean> all ;
    private ArrayList<PersonBean> list = new ArrayList<>() ;

    @Override
    protected void init() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        all = (ArrayList<PersonBean>)bundle.getSerializable("pearsonList");
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        adaper = new SearchAdaper(this,list);
        recyclerView.setAdapter(adaper);
        filterList(null);
        initListener();
    }

    private void initListener() {
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                if ((editText.getText().toString()).isEmpty()) {
//                    tvEC.setText("取消");
//                    ivClear.setVisibility(View.GONE);
//                } else {
//                    tvEC.setText("搜索");
//                    ivClear.setVisibility(View.VISIBLE);
//                }
                handler.removeCallbacks(runnable);
                handler.postDelayed(runnable, 500);
                List<String> stringList = new ArrayList<>();
                String tmp = editText.getText().toString();
                if (PinyingUtils.isChinese(tmp)) {
                    stringList.add(tmp);
                } else if (PinyingUtils.isEnglish(tmp)) {
                    stringList.add(tmp.toLowerCase());
                    stringList.add(tmp.toUpperCase());
                } else {
                    stringList.add(tmp);
                }
                adaper.setSearchTxt(stringList);
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    if ((editText.getText().toString()).isEmpty()) {
                        showToast("请输入搜索关键字");
                        return true;
                    }
                    return true;
                }
                return false;
            }
        });
    }
    /**
     * 筛选列表
     */
    private void filterList(String filter) {
        Log.e("11111111111111111","---------"+filter);
        list.clear();
        //添加空列表
        adaper.setNewData(list);
        recyclerView.scrollToPosition(0);
        if (filter == null || filter.trim().length() == 0) {
            Log.e("11111111111111111","-----进来了----"+filter);
            adaper.setNewData(all);
            recyclerView.scrollToPosition(0);
            return;
        }
        boolean isChinese = PinyingUtils.isChinese(filter);//如果是中文则直接匹配

        for (int i = 0; i < all.size(); i++) {
            String name = all.get(i).getName();
            String phone = all.get(i).getPhone();
            if (name == null || name.trim().length() == 0)
                continue;
            if (isChinese) {
                if (name.contains(filter))//中文直接比对即可
                    list.add(all.get(i));
            } else {
                String firstSpell = PinyingUtils.cn2FirstSpell(name);
                String spell = PinyingUtils.cn2Spell(name);
                if (firstSpell.toUpperCase().contains(filter.toUpperCase()) || spell.toUpperCase().contains(filter.toUpperCase())) {//如果首字母匹配
                    if (!list.contains(all.get(i)))
                        list.add(all.get(i));
                } else if (phone != null && phone.trim().length() > 0 && phone.contains(filter)) {//当电话号码满足时也会加入进列表
                    if (!list.contains(all.get(i)))
                        list.add(all.get(i));
                }
            }
        }
        adaper.notifyDataSetChanged();
        recyclerView.scrollToPosition(0);
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            handler.sendEmptyMessage(0);
        }
    };
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            filterList(editText.getText().toString());
        }
    };
}
